package com.cxyjy.common.constants;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @Author: jony
 * @Date : 2025/4/17 23:07
 * @VERSION v1.0
 */

@Component
public class ImageMatchConstants {
    public static volatile String BAIDU_TOKEN;
    private static final String CLIENT_ID = "qy3tzvbvxfUsvsrjJZIjlOW9";
    private static final String CLIENT_SECRET = "zAaJdVk225gEEjFicbKEjDZiCD6iDuaz";

    public static volatile URL IMAGE_MATCH_URL;
    public static volatile URL IMAGE_ADD_URL;
    public static volatile URL IMAGE_DELETE_URL;
    public static volatile URL IMAGE_UPDATE_URL;

    public static final String BAIDU_API_BASE_URL_STR = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/";

    //每29天更新一次，百度API 30天过期
    @Scheduled(fixedDelay = 29L * 24 * 60 * 60 * 1000)
    public static void refreshToken() {
        try {
            BAIDU_TOKEN = fetchTokenFromBaidu();
            updateUrls();
            System.out.println("Token刷新成功：" + BAIDU_TOKEN.substring(0, 8) + "...");
        } catch (Exception e) {
            System.err.println("Token刷新失败: " + e.getMessage());
        }
    }

    private static String fetchTokenFromBaidu() throws Exception {
        String urlStr = "https://aip.baidubce.com/oauth/2.0/token"
                + "?grant_type=client_credentials"
                + "&client_id=" + CLIENT_ID
                + "&client_secret=" + CLIENT_SECRET;

        try (InputStream is = new URL(urlStr).openStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {

            // 读取 JSON 字符串
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }

            // 解析 JSON 并提取 access_token
            JSONObject jsonObject = JSON.parseObject(jsonBuilder.toString());
            return jsonObject.getString("access_token");
        }
    }

    private static void updateUrls() throws MalformedURLException {
        IMAGE_MATCH_URL = new URL(BAIDU_API_BASE_URL_STR + "search?access_token=" + BAIDU_TOKEN);
        IMAGE_ADD_URL = new URL(BAIDU_API_BASE_URL_STR + "add?access_token=" + BAIDU_TOKEN);
        IMAGE_DELETE_URL = new URL(BAIDU_API_BASE_URL_STR + "delete?access_token=" + BAIDU_TOKEN);
        IMAGE_UPDATE_URL = new URL(BAIDU_API_BASE_URL_STR + "update?access_token=" + BAIDU_TOKEN);
    }
}
